package com.gcit.seniorWish.web.modular.system.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.gcit.seniorWish.web.core.annotion.BussinessLog;
import com.gcit.seniorWish.web.core.annotion.Permission;
import com.gcit.seniorWish.web.common.constant.dictmap.DeptDict;
import com.gcit.seniorWish.web.common.constant.factory.ConstantFactory;
import com.gcit.seniorWish.web.common.constant.factory.PageFactory;
import com.gcit.seniorWish.web.core.exception.BizExceptionEnum;
import com.gcit.seniorWish.web.common.persistence.dao.DeptMapper;
import com.gcit.seniorWish.web.common.persistence.model.Dept;
import com.gcit.seniorWish.core.base.controller.BaseController;
import com.gcit.seniorWish.core.exception.GunsException;
import com.gcit.seniorWish.web.core.log.LogObjectHolder;
import com.gcit.seniorWish.core.node.ZTreeNode;
import com.gcit.seniorWish.core.util.ToolUtil;
import com.gcit.seniorWish.web.modular.system.dao.DeptDao;
import com.gcit.seniorWish.web.modular.system.service.IDeptService;
import com.gcit.seniorWish.web.modular.system.warpper.DeptWarpper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 部门控制器
 *
 * @author fengshuonan
 * @Date 2017年2月17日20:27:22
 */
@Controller
@RequestMapping("/dept")
public class DeptController extends BaseController {

    private String PREFIX = "/system/dept";

    @Resource
    DeptDao deptDao;

    @Resource
    private IDeptService deptService;

    /**
     * 跳转到部门管理首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/dept.html";
    }

    /**
     * 跳转到添加部门
     */
    @RequestMapping("/dept_add")
    public String deptAdd() {
        return PREFIX + "/deptAdd.html";
    }

    /**
     * 跳转到修改部门
     */
    @RequestMapping("/dept_update/{deptId}")
    public String deptUpdate(@PathVariable String deptId, Model model) {
        Dept dept = deptService.selectById(deptId);
        model.addAttribute(dept);
        model.addAttribute("pName", ConstantFactory.me().getDeptName(dept.getPid()));
        LogObjectHolder.me().set(dept);
        return PREFIX + "/deptInfo.html";
    }

    /**
     * 获取部门的tree列表
     */
    /**
    *
    * @param pid 节点id，查询其子节点（主要用于异步加载）
     *@param initId 初始加载的id
    * @author gaozhichang
    * @date 2018-03-01 下午 2:04
    */
    @RequestMapping(value = "/tree")
    @ResponseBody
    public List<ZTreeNode> tree(String pid,String initId) {
        List<String> pids=null;
        //当初始选中的id存在时，加载该节点以上所有同级的节点
        if(StrUtil.isNotBlank(initId)&&!initId.equals("0")){
            pids = ConstantFactory.me().getParentdeptIds(initId);
        }
        List<ZTreeNode> tree = this.deptDao.tree(pid,pids);
        if(StrUtil.isBlank(pid)){
            tree.add(ZTreeNode.createParent());
        }
        return tree;
    }

    /**
     * 新增部门
     */
    @BussinessLog(value = "添加部门", key = "simplename", dict = DeptDict.class)
    @RequestMapping(value = "/add")
    @Permission
    @ResponseBody
    public Object add(Dept dept) {
        if (ToolUtil.isOneEmpty(dept, dept.getName())) {
            throw new GunsException(BizExceptionEnum.REQUEST_NULL);
        }
        //完善pids,根据pid拿到pid的pids
        deptSetPids(dept);
        return this.deptService.insert(dept);
    }

    /**
     * 获取所有部门列表
     */
    @RequestMapping(value = "/list")
    @Permission
    @ResponseBody
    public Object list(String pid,String deptName) {
        EntityWrapper<Dept> ew = new EntityWrapper<Dept>();
        Page<Map<String, Object>> page = new PageFactory<Map<String, Object>>().defaultPage();
//        if(pid!=null&&pid!=0L){
        if(StrUtil.isNotBlank(pid)){
            ew.like("pids","["+pid+"]");
        }
        if(StrUtil.isNotBlank(deptName)){
            ew.like("name",deptName);
        }
        page = deptService.selectMapsPage(page, ew);
        page.setRecords((List<Map<String, Object>>) new DeptWarpper(page.getRecords()).warp());
        return packForBT(page);
    }

    /**
     * 部门详情
     */
    @RequestMapping(value = "/detail/{deptId}")
    @Permission
    @ResponseBody
    public Object detail(@PathVariable("deptId") String deptId) {
        return deptService.selectById(deptId);
    }

    /**
     * 修改部门
     */
    @BussinessLog(value = "修改部门", key = "simplename", dict = DeptDict.class)
    @RequestMapping(value = "/update")
    @Permission
    @ResponseBody
    public Object update(Dept dept) {
        if (ToolUtil.isEmpty(dept) || dept.getId() == null) {
            throw new GunsException(BizExceptionEnum.REQUEST_NULL);
        }
        deptSetPids(dept);
        deptService.updateById(dept);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除部门
     */
    @BussinessLog(value = "删除部门", key = "deptId", dict = DeptDict.class)
    @RequestMapping(value = "/delete")
    @Permission
    @ResponseBody
    public Object delete(@RequestParam String deptId) {

        //缓存被删除的部门名称
        LogObjectHolder.me().set(ConstantFactory.me().getDeptName(deptId));

        deptService.deleteDept(deptId);

        return SUCCESS_TIP;
    }

    private void deptSetPids(Dept dept) {
        if (ToolUtil.isEmpty(dept.getPid()) || dept.getPid().equals("0")) {
            dept.setPid("0");
            dept.setPids("[0],");
        } else {
            String pid = dept.getPid();
            Dept temp = deptService.selectById(pid);
            String pids = temp.getPids();
            dept.setPid(pid);
            dept.setPids(pids + "[" + pid + "],");
        }
    }
}
